package handler

import (
	"context"
	"product/common"
	"product/domain/model"
	"product/domain/service"
	"product/proto"
)

type ProductHandler struct {
	DataService service.IProductDataService
}

func (p *ProductHandler) AddProduct(ctx context.Context, info *product.ProductInfo, response *product.ProductResponse) error {
	productCreated := &model.Product{}
	err := common.SwapTo(info, productCreated)
	if err != nil {
		return err
	}
	id, err := p.DataService.AddProduct(productCreated)
	if err != nil {
		return err
	}
	response.ProductId = id
	return nil
}

func (p *ProductHandler) FindProductByID(ctx context.Context, request *product.ProductIDRequest, info *product.ProductInfo) error {
	prod, err := p.DataService.FindProductByID(request.ProductId)
	if err != nil {
		return err
	}
	err = common.SwapTo(prod, info)
	if err != nil {
		return err
	}
	return nil
}

func (p *ProductHandler) UpdateProduct(ctx context.Context, info *product.ProductInfo, response *product.UpdateProductResponse) error {
	productUpdated := &model.Product{}
	err := common.SwapTo(info, productUpdated)
	if err != nil {
		return err
	}
	err = p.DataService.UpdateProduct(productUpdated)
	if err != nil {
		response.Msg = "更新失败!"
		return err
	}
	response.Msg = "更新成功!"
	return nil
}

func (p *ProductHandler) DeleteProductByID(ctx context.Context, request *product.ProductIDRequest, response *product.DeleteProductResponse) error {
	err := p.DataService.DeleteProduct(request.ProductId)
	if err != nil {
		response.Msg = "删除失败!"
		return err
	}
	response.Msg = "删除成功!"
	return nil
}

func (p *ProductHandler) FindAll(ctx context.Context, request *product.ProductAllRequest, response *product.ProductAllResponse) error {
	products, err := p.DataService.FindAllProducts()
	if err != nil {
		return err
	}
	prods := make([]*product.ProductInfo, len(products))
	for _, pro := range products {
		p := product.ProductInfo{}
		err := common.SwapTo(pro, p)
		if err != nil {
			return err
		}
		prods = append(prods, &p)
	}
	response.Products = prods
	return nil
}
